<template>
    <div class="flex-container">
      <el-select-v2
          v-model="param.fromCost"
          :options="options"
          placeholder="租金下限"
          style="width: 240px; margin-right: 20px;"
          @change="getRooms"
      />
      <el-select-v2
          v-model="param.toCost"
          :options="filteredCostOptions"
          placeholder="租金上限"
          :disabled="isSelectDisabled"
          style="width: 240px; margin-right: 20px;"
          @change="getRooms"
      />
      <el-input v-model="param.address" placeholder="请输入地址" style="width: 240px ;margin-right:20px" @input="getRooms"/>
      <el-input v-model="param.type" placeholder="请输入户型" style="width: 240px ;margin-right:20px" @input="getRooms"/>
    </div>
  <div  v-loading="loading" >
    <el-row :gutter="20">
      <el-col v-for="room in rooms" :key="room.id" :span="8">
        <el-card :body-style="{ padding: '0px' }" class="room-card">

            <img :src="`${OpenAPI.BASE}/common/download?name=${room.image}`" class="image" @click="getRoom(room.id),dAddress=room.address,rentParam.room=room.id"/>

          <div style="padding: 14px; display: flex; flex-direction: row;">
            <span style="margin-right:10px">{{ room.address }}</span>
            <span style="margin-right:10px">
              <span>{{ room.cost }}</span>
            </span>
            <span style="margin-right:10px">{{ room.type }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty v-if="rooms.length === 0" description="暂无数据"></el-empty>

    <el-pagination
        v-if="rooms.length"
        class="pageList"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="param.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        v-model:current-page="page"
        @current-change="handleCurrentChange"
    ></el-pagination>


    <el-drawer v-model="drawer" title="I am the title" :with-header="false">
      <div class="product-detail">
        <el-card class="product-card">
          <el-divider></el-divider>
          <!--      <el-row v-if="room">-->
          <!--        <el-col :span="12">-->
          <!--          <h1>{{ room.roomNumber }}</h1>-->
          <!--          <p>Type: {{ room.type }}</p>-->
          <!--          <p>Cost: {{ room.cost }}</p>-->
          <!--          <p>Cash Pledge: {{ room.cashPledge }}</p>-->
          <!--          <p>Building: {{ room.building }}</p>-->
          <!--          <p>Description: {{ room.description }}</p>-->
          <!--          <p>address: {{ address}}</p>-->
          <!--        </el-col>-->
          <!--      </el-row>-->

          <el-descriptions :title="`房间号${room.roomNumber}`" v-if="room">
            <el-descriptions-item label="房租/月">{{ room.cost }}</el-descriptions-item>
            <el-descriptions-item label="押金">{{ room.cashPledge }}</el-descriptions-item>
            <el-descriptions-item label="房间详情">{{room.description}}</el-descriptions-item>
            <el-descriptions-item label="类型">
              <el-tag size="small">{{room.type}}</el-tag>
            </el-descriptions-item>




            <el-descriptions-item label="Address"
            >{{dAddress}}</el-descriptions-item
            >
          </el-descriptions>
          <div v-else>
            Loading...
          </div>
        </el-card>
      </div>
      <br>

      <el-date-picker
          v-model="rentParam.rentFrom"
          placeholder="请选择起始时间"
          :disabled-date="disabledDate"

      />

      <el-input-number v-model="num" :min="0" :max="36"  @change="getToRent" :style="{marginBottom: '10px' }"/>
      <el-button type="primary" :loading="loading" @click="showConfirmationDialog">{{
          loading ? 'Submitting ...' : 'Submit'
        }}</el-button>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive, watch, computed} from 'vue';
import {ElMessage, ElMessageBox, MessageBox} from 'element-plus';
import {OpenAPI, RentDetaioDto, RoomManageControllerService, RoomRequestParam} from '../../generated';

const rooms = ref([]);
const total = ref(0);
const page = ref(1);
let drawer = ref(false)
let dAddress=ref();
const room=ref();
const num=ref(0);
const param = reactive({
  address: "",
  current: page.value,
  fromCost: "",
  pageSize: 10, // 默认每页显示10条
  toCost: "",
  type: ""
} as unknown as RoomRequestParam);

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}

const showConfirmationDialog = () => {
  // 使用 ElMessageBox 弹窗
  ElMessageBox.alert(`租房时间为 ${rentParam.rentFrom} 至 ${rentParam.rentTo}，请确认`, '确认租房时间', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击确认按钮后的回调，可以在这里发起请求
    submitCent();
    getRooms();
  }).catch(() => {
    // 用户点击取消按钮后的回调
    console.log("取消")
  });
};

const costOptions = ref([
  { value: '', label: '租金上限不限' },
  { value: '1000', label: '1000' },
  { value: '2000', label: '2000' },
  { value: '3000', label: '3000' },
]);

// 计算属性，用于判断是否禁用 el-select-v2
const isSelectDisabled = computed(() => {
  return param.fromCost === '';
});

// 计算属性，过滤掉比 param.fromCost 小的选项
const filteredCostOptions = computed(() => {
  return costOptions.value.filter(option => option.value === '' || parseInt(option.value) > parseInt(param.fromCost));
});

// 监听 param.fromCost 的变化
watch(() => param.fromCost, (newVal) => {
  // 可以在这里进行其他操作
});
const rentParam=reactive({
  rentFrom:'',
  rentTo:'',
  room:'',
} as unknown as RentDetaioDto);

const submitCent= async () => {
  try {
    // 格式化日期为字符串
    rentParam.rentFrom = rentParam.rentFrom.toLocaleString();
    rentParam.rentTo = rentParam.rentTo.toLocaleString();

    const response = await RoomManageControllerService.customerRentUsingPost(rentParam);
    if (response.code === 200) {
      ElMessage.success("订单添加成功");
    } else {
      ElMessage.error('订单添加失败:', response.message);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};

let loading=false;

const options = ref([
  { value: '', label: '租金下限不限' },
  { value: '0', label: '0' },
  { value: '1000', label: '1000' },
  { value: '2000', label: '2000' },
  { value: '3000', label: '3000' },
])

const getToRent = () => {
  // 检查 rentParam.rentFrom 和 num 是否存在
  if (rentParam.rentFrom && num) {
    // 复制 rentFrom 的日期
    const rentTo = new Date(rentParam.rentFrom);

    // 将日期增加 num 个月
    rentTo.setMonth(rentTo.getMonth() + num.value);

    // 更新 rentParam.rentTo
    rentParam.rentTo = rentTo.toLocaleDateString('en-CA'); // 使用合适的语言标识符

    // 格式化 rentFrom
    rentParam.rentFrom = new Date(rentParam.rentFrom).toLocaleDateString('en-CA');
  } else {
    console.error("rentFrom and num must be defined");
  }
}

const getRooms = async () => {
  try {
    const response = await RoomManageControllerService.listPageUsingPost1(param);
    if (response.code === 200) {
      rooms.value = response.result.list;
      total.value = response.result.total;
      loading=false;
    } else {
      console.error('Failed to fetch rooms:', response.message);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};

const getRoom = async (id) => {
  drawer.value = true;
  try {
    const response = await RoomManageControllerService.getDetailUsingGet(id);
    if (response.code === 200) {
      room.value = response.result;
    } else {
      console.error('Failed to fetch room:', response.message);
    }
  } catch (error) {
    console.error('Error fetching room:', error);
  }
};
const handleSelectionChange = (selection: any) => {
  console.log('Selected Rooms:', selection);
};

const handleSizeChange = (pageSize: number | undefined) => {
  param.pageSize = pageSize;
  getRooms();
};

const handleCurrentChange = (currentPage: number | undefined) => {
  param.current = currentPage;
  getRooms();
};

onMounted(() => {
  getRooms();
});
</script>

<style scoped>
.pageList {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
}

.room-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  transition: border 0.3s ease-in-out 0.2s, transform 0.3s ease-in-out 0.2s;
  margin-bottom: 20px;
}

.room-card:hover {
  border: 1px solid #409EFF;
  transform: translateY(-5px);
}

.room-info {
  display: flex;
  flex-direction: column;
  padding: 14px;
  text-align: center;
}

.room-info span {
  margin: 8px 0;
}

.flex-container {
  display: flex;
  margin-bottom: 20px;
}
</style>
